Pokerface.addComponent(new Pokerface.Component.extend({
    _pauseUpdates: false,

    // protected methods
    _update: function(self, timeout) {
        setTimeout(function(){
            $.ajax({
                url: '/game/list',
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    $('#table_loading').remove();
                    if (self._pauseUpdates) {
                        return;
                    }
                    $('.table_row').remove();
                    for (var i in data) {
                        var table = data[i];
                        var row = $('#proto').clone();
                        row.find('.table_name').text(table.name);
                        row.find('.table_max_players').text(table.playersCount);
                        row.find('.table_players_count').text(table.playersActual);
                        row.find('input').val(table.id);
                        if (table.playersActual >= table.playersCount) {
                            row.find('.table_play').html('');
                        }
                        row.removeAttr('id').addClass('table_row').show().appendTo('#games_list table');
                    }
                },
                complete: function() {
                    self._update(self, 3000);
                }
            });
        }, timeout);
    },

    _showTable: function(id) {
        $('#games_list').fadeOut(200, function(){
            $('#table').fadeIn(200);
        });
        Pokerface._currentTableId = id;
        Pokerface.start('table');
    },

    // public
    getName: function(){
       return 'tableList';
    },

    start: function() {
        var self = this;
        this._pauseUpdates = false;
        this._update(this, 0);
        $('.connect_table').die().live('click', function(){
            var id = $(this).siblings('input').val();
            var bank = prompt('Enter your bank value');
            $.ajax({
                url: '/game/sit',
                type: 'POST',
                dataType: 'json',
                data: 'id=' + id + '&game_player_bank=' + bank,
                success: function(data){
                    self._pauseUpdates = true;
                    self._showTable(id);
                }
            });
            return false;
        });
    }
})());